# coding=utf-8
"""
作者：董新强 
创建时间：2020-3-21
描述：问题库
"""
import random

from db_models.cat_questions import CatQuestions as Question
from db_models.updated_questions import UpdatedQuestions
from framework.db_session import DbSession
from framework.schedule import Schedule


class QuestionBank:
    _item_info_dict = {}
    _latest_question_update_time = 0  # 最大更新时间戳(以数据库记录的时间为准)

    @staticmethod
    def _load_questoins():
        """载入题库完成"""
        with DbSession.create() as db:
            query = db.query(Question.id, Question.aid, Question.a, Question.b, Question.c, Question.d, Question.info, Question.exp_rate)
            for id, aid, a, b, c, d, info, exp_rate in query:
                QuestionBank._add_or_update_question_bank_dict(a, aid, b, c, d, exp_rate, id, info)
            print('载入题库完成')

    @staticmethod
    def _add_or_update_question_bank_dict(a, aid, b, c, d, exp_rate, id, info):
        """更新具体有一条记录"""
        if aid in QuestionBank._item_info_dict:  # 添加数据到已存在的维度中去
            QuestionBank._item_info_dict[aid][id] = [a, b, c, d, exp_rate, info]
        else:  # 如果改维度还没加载到内存中,则新增改维度
            QuestionBank._item_info_dict[aid] = {id: [a, b, c, d, exp_rate, info]}

    @staticmethod
    def get_item_params(aid, selected_item_id_ls):
        qdict = QuestionBank._item_info_dict.get(aid)
        if not qdict:
            return []

        ls = []
        for qid in selected_item_id_ls:
            ls.append(qdict[qid][0:5])
        return ls

    @staticmethod
    def get_item_nearest(aid, idx, theta):
        items = QuestionBank._item_info_dict.get(aid)
        if not items:
            return []

        ls = []
        for k, v in items.items():
            ls.append((k, abs(v[idx] - theta)))

        ls.sort(key=lambda a: a[1])  # 逆序排列
        return ls

    @staticmethod
    def get_qid(aid):
        qdict = QuestionBank._item_info_dict.get(aid)
        if not qdict:
            return None
        return random.sample(qdict.keys(), 1)[0]

    @staticmethod
    def _update_memory_banks():
        """
        更新内存题库
        """
        try:
            updated_question_count = 0
            with DbSession.create() as db:
                question_ls = db.query(Question.id, Question.aid, Question.a, Question.b, Question.c, Question.d, Question.info, Question.exp_rate, UpdatedQuestions.update_time) \
                    .filter(Question.id == UpdatedQuestions.qid) \
                    .filter(UpdatedQuestions.update_time > QuestionBank._latest_question_update_time)

                for id, aid, a, b, c, d, info, exp_rate, update_time in question_ls:
                    if update_time > QuestionBank._latest_question_update_time:  # 记录最新的时间
                        QuestionBank._latest_question_update_time = update_time

                    # 更新试题
                    QuestionBank._add_or_update_question_bank_dict(a, aid, b, c, d, exp_rate, id, info)
                    updated_question_count += 1

            if updated_question_count:
                print('更新 [%d] 条项目' % (updated_question_count,))

        except Exception as e:
            print('_update_memory_banks=>', e)

    @staticmethod
    def update_memory_banks_periodic():
        """
        定时更新内存题库参数
        """
        Schedule().start(QuestionBank._update_memory_banks, 500)  # 每5分钟更新一次参数


QuestionBank._load_questoins()
